using UnityEngine;

namespace BF
{
    public static class GameObjectExtension
    {
        public static GameObject Layer(this GameObject self, int layer)
        {
            if (self)
            {
                self.layer = layer;
            }
            return self;
        }

        public static GameObject Layer(this GameObject self, string layerName)
        {
            if (self)
            {
                self.layer = LayerMask.NameToLayer(layerName);
            }
            return self;
        }

        public static T GetOrAddComponent<T>(this GameObject self) where T : Component
        {
            if (!self)
            {
                throw new System.NullReferenceException("Null object can not get component!");
            }
            return self.GetComponent<T>() ?? self.AddComponent<T>();
        }

        public static void RemoveComponent<K>(this GameObject self) where K : Component
        {
            if (!self) return;

            K ke = self.GetComponent<K>();
            if (ke != null)
            {
                UnityEngine.Object.Destroy(ke.gameObject);
            }
        }

        public static void ChangeCanvasSorting(this GameObject self, string name = "Default", int order = 0)
        {
            if (!self) return;

            Canvas canvas = self.GetComponent<Canvas>();
            if (canvas == null)
                canvas = self.AddComponent<Canvas>();
            canvas.overrideSorting = true;
            canvas.sortingLayerName = name;
            canvas.sortingOrder = order;
        }

        public static void ChangeCanvasUnsorting(this GameObject self)
        {
            if (!self) return;

            Canvas canvas = self.GetComponent<Canvas>();
            if (canvas != null)
            {
                canvas.overrideSorting = false;
            }
        }
    }
}
